package com.lanou.dllo.vc.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Toast;

import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.exceptions.EaseMobException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import com.lanou.dllo.vc.MyApplication;
import com.lanou.dllo.vc.R;

import com.lanou.dllo.vc.activity.ScanActivty;

import com.lanou.dllo.vc.adapter.NewsListAdapter;
import com.lanou.dllo.vc.greendao.ChatMessage;

import com.lanou.dllo.vc.util.RGBLuminanceSource;
import com.zbar.lib.CaptureActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by dllo on 15/11/16.
 */
public class NewsFragment extends Fragment implements View.OnClickListener, PopupMenu.OnMenuItemClickListener {

    private ListView listView;
    private ImageView news_moreIv, qRIv;
    private static int QR_WIDTH = 600;
    private static int QR_HEIGHT = 600;
    private String myName, username;
    private NewsListAdapter adapter;
    private InputMethodManager inputMethodManager;
    private List<EMConversation> conversationList;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }


    /**
     * 在这个方法里面，获取传入的数据
     *
     * @param savedInstanceState
     */
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    /**
     * 这个方法里面加载布局
     */
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news, null);

        return view;
    }


    /**
     * 控件初始化在这写
     */
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    private void initView(View v) {
        listView = (ListView) v.findViewById(R.id.fragment_listView);
        news_moreIv = (ImageView) v.findViewById(R.id.news_moreIv);
        news_moreIv.setOnClickListener(this);
        qRIv = (ImageView) v.findViewById(R.id.QRIv);
        qRIv.setOnClickListener(this);

        EventBus.getDefault().register(this);
        inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        adapter = new NewsListAdapter(getActivity());
        listView.setAdapter(adapter);
        // 会话列表加载所有会话

        conversationList = loadConversationList();
        adapter.addData(conversationList);


    }

    /**
     * 搜索监听
     * */
//        msgSearch_Et.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
////                if (s != null && s.length() == 0) {
////                    msgSearch_Et.setText(null);
////                }
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
////                if (s != null && s.length() == 0) {
////                    msgSearch_Et.setText(null);
////                }
//                if (s != null && s.length() > 0) {
//                    search_Ll.setVisibility(View.GONE);
//                    adapter.getFilter().filter(s);
//                }
////                else if (s != null && s.length() == 0) {
////                    msgSearch_Et.setText(null);
////                }
//                else {
//                    search_Ll.setVisibility(View.VISIBLE);
//                    conversationList.clear();
//                    conversationList.addAll(loadConversationList());
//                    adapter.addData(conversationList);
//                }
//            }
//        });
//
//    }


    /**
     * 数据初始化在这写
     *
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        EMChatManager.getInstance().registerEventListener(new EMEventListener() {
                                                              @Override
                                                              public void onEvent(EMNotifierEvent emNotifierEvent) {
                                                                  EMMessage emMessage = (EMMessage) emNotifierEvent.getData();
                                                              }
                                                          }, new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage}
        );
        myName = MyApplication.getUserName();

        username = EMChatManager.getInstance().getCurrentUser();
//        username = getActivity().getIntent().getStringExtra("username");
        msgListener();

    }

    /**
     * 更改设置之后更新列表的显示
     */

    public void onEventMainThread(String isAcceptNews) {
        if (isAcceptNews != null) {
            adapter = new NewsListAdapter(getActivity());
            listView.setAdapter(adapter);
            adapter.addData(loadConversationList());
        }
    }

    public void onEventMainThread(Double a) {
        conversationList.clear();
        conversationList.addAll(loadConversationList());
        adapter = new NewsListAdapter(getActivity());
        listView.setAdapter(adapter);
        adapter.addData(conversationList);
    }

    /**
     * 获取会话列表
     *
     * @return
     */
    protected List<EMConversation> loadConversationList() {
        // 获取所有会话，包括陌生人
        Hashtable<String, EMConversation> conversations = EMChatManager.getInstance().getAllConversations();

        // 过滤掉messages size为0的conversation
        /**
         * 如果在排序过程中有新消息收到，lastMsgTime会发生变化
         * 影响排序过程，Collection.sort会产生异常
         * 保证Conversation在Sort过程中最后一条消息的时间不变
         * 避免并发问题
         */
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        // 同步
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    if (conversation.getType() != EMConversation.EMConversationType.ChatRoom) {
                        sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                    }
                }
            }
        }
        try {
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }


    /**
     * 根据最后一条消息的时间排序
     * comparator类是比较用的
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first == con2.first) {
                    return 0;
                } else if (con2.first > con1.first) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
    }

    /**
     * 隐藏软键盘
     */
    protected void hideSoftKeyboard() {
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 过滤 输入的str
     */
//    public void filter(CharSequence str) {
//        adapter.getFilter().filter(str);
//    }

    /**
     * 接收消息的监听
     */
    public void msgListener() {
        EMChatManager.getInstance().registerEventListener(
                new EMEventListener() {

                    @Override
                    public void onEvent(EMNotifierEvent event) {

                        switch (event.getEvent()) {
                            case EventNewMessage: // 接收新消息
                            {
//                                conversationList.clear();
//                                conversationList.addAll(loadConversationList());
//                                adapter.addData(loadConversationList());
                                adapter.notifyDataSetChanged();
                                break;
                            }
                            case EventDeliveryAck: {//接收已发送回执
                                break;
                            }
//
//                            case EventNewCMDMessage: {//接收透传消息
//
//                                break;
//                            }
//
                            case EventReadAck: {//接收已读回执

                                break;
                            }
//
//                            case EventOfflineMessage: {//接收离线消息
//                                List<EMMessage> messages = (List<EMMessage>) event.getData();
//                                break;
//                            }
//
//                            case EventConversationListChanged: {//通知会话列表通知event注册（在某些特殊情况，SDK去删除会话的时候会收到回调监听）
//
//                                break;
//                            }

                            default:
                                break;
                        }
                    }
                }
        );
    }

    @Override
    public void onPause() {
        super.onPause();
//        msgSearch_Et.setText(null);
    }

    @Override
    public void onResume() {
        super.onResume();
        conversationList.clear();
        conversationList.addAll(loadConversationList());
        adapter.addData(loadConversationList());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.news_moreIv:
                PopupMenu menu = new PopupMenu(getContext(), v);//建立popupMenu对象
                menu.getMenuInflater().inflate(R.menu.menu_news_more, menu.getMenu());//菜单xml资源
                menu.setOnMenuItemClickListener(this);
                menu.show();
                break;
            case R.id.QRIv:
                qRIv.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.qRcode:
                JSONObject json = new JSONObject();
                try {
                    json.put("name", myName);
                    createImage(json.toString());

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                break;
            case R.id.scan:
                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                getActivity().startActivityForResult(intent, 444);
                break;
        }

        return false;

    }

    // 生成QR图
    private void createImage(String content) {
        try {
            // 把输入的文本转为二维码
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

            BitMatrix bitMatrix = new QRCodeWriter().encode(content,
                    BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);

            int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
            for (int y = 0; y < QR_HEIGHT; y++) {
                for (int x = 0; x < QR_WIDTH; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * QR_WIDTH + x] = 0xff000000;
                    } else {
                        pixels[y * QR_WIDTH + x] = 0xffffffff;
                    }

                }
            }

            Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
                    Bitmap.Config.ARGB_8888);

            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
            if (bitmap != null) {
                qRIv.setVisibility(View.VISIBLE);
                qRIv.setImageBitmap(bitmap);
            }

        } catch (WriterException e) {
            e.printStackTrace();
        }
    }


}
